const {ccclass, property} = cc._decorator;

@ccclass
export default class Player extends cc.Component {

    @property
    maxHealth:number=6;

    @property
    maxBullet:number=1000;

    @property(cc.ProgressBar)
    HPBar:cc.ProgressBar=null;

    private _health:number=0
    set health(val:number){
        this._health=val;  
        if(this._health>=this.maxHealth){
            this._health=this.maxHealth;
        }
        if(this.HPBar){
            this.HPBar.progress=this._health/this.maxHealth;
        }
    }
    get health(){return this._health;}
    _isHurt:boolean=false;

    private _bullet:number

    get bullet(){
        return this._bullet;
    }
    set bullet(val:number){
        this._bullet=val;
        this.node.emit('fire',this._bullet);
    }

    public static instance:Player=null

    onLoad () {
        Player.instance=this;

        this.node.on('get-supply',this.getSupply,this);
        this.node.on('get-lift',this.getLift,this);
    }

    start () {
        this.health=this.maxHealth;
        this.bullet=this.maxBullet;
    
    }

    getSupply(num:number){
        this.bullet+=num;
    }

    getLift(life:number){
        this.health+=life;
        
    }

    hurt(damage:number){
        if(this._isHurt==true){
            return;
        }
        this.health-=damage;
        if(this.health<=0){
            this.node.emit('player-die');
        }
        this._isHurt=true;
        
        if(this.health==0){
            this.node.active=false;
            cc.game.emit('game-over');
        }

        cc.tween(this.node)
			.to(0.25, { color: cc.color(255, 0, 0) })
			.to(0.25, { color: cc.color(255, 255, 255) })
            .call(()=>{
                this._isHurt=false;
            })
			.start();
    }

    onPreSolve(contact, self: cc.Collider, other: cc.Collider) {
		if ((other.node.group == "zombie")) {
            this.hurt(1);
			//other.node.destroy();
		}
	}
    
    update (dt) {
        if(this.node.getBoundingBox().intersects(this.HPBar.node.getBoundingBox())){
            this.HPBar.node.opacity=100;
        }
        else{
            this.HPBar.node.opacity=255;
        }
    }
}
